<template>
  <div id="box" v-loading="loading"></div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { loadJs, loadCss } from '@/utils'
import request from '@/config/axios'
const props = defineProps({
  value: {
    type: String,
    default() {
      return ''
    }
  },
  amisJson: {
    type: Object,
    required: false
  },
  amisType: {
    type: String,
    required: false
  }
})
const emit = defineEmits(['update:value'])
const loading = ref(false)
const initAmis = (schema) => {
  // @ts-ignore
  let amis = amisRequire('amis/embed')
  amis.embed(
    '#box',
    schema,
    {
      data: props.value ? JSON.parse(props.value) : {}
    },
    {
      useMobileUI: false,
      tracker: (eventTrack, props) => {
        console.log(eventTrack, props)
        if (!eventTrack.eventData) {
          return
        }
        if (eventTrack.eventData?.name === 'flat') {
          return
        }
        let a = { [eventTrack.eventData?.name]: eventTrack.eventData?.value }
        let b = props?.store?.data || {}
        let r = b ? Object.assign(b, a) : a
        emit('update:value', JSON.stringify(r))
      }
    }
  )
  loading.value = false
}
onMounted(() => {
  let schema
  loading.value = true
  //const publicPath = import.meta.env.VITE_PUBLIC_PATH || '/'
  loadCss('https://lib.baomitu.com/amis/3.3.0/sdk.min.css')
  loadCss('https://lib.baomitu.com/amis/3.3.0/iconfont.min.css')
  loadJs('https://lib.baomitu.com/amis/3.3.0/sdk.min.js').then(() => {
    if (props.amisType) {
      request.get({ url: '/infra/base/amis/getAmis/' + props.amisType }).then((data) => {
        schema = JSON.parse(data.jsonData)
        initAmis(schema)
      })
    } else {
      schema = props.amisJson
      initAmis(schema)
    }
  })
})
</script>
<style>
#box {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
</style>
